<template>
  <div>
    <BreadCrumb pathOne="咨询公告管理"></BreadCrumb>
    <el-form :inline="true">
      <el-form-item label="咨询公告名" size="large">
        <el-input
          size="large"
          clearable
          v-model="bulletinName"
          placeholder="请输入咨询公告名"
        ></el-input>
      </el-form-item>
      <el-form-item label="公告内容" size="large">
        <el-input
          size="large"
          clearable
          v-model="inforText"
          placeholder="请输入公告内容"
        ></el-input>
      </el-form-item>
      <el-form-item size="large">
        <el-button type="primary" @click="query">搜索</el-button>
        <el-button type="primary" @click="createOrUpdate('')">新增咨询公告</el-button>
        <el-button type="danger" @click="batchDelete">批量删除</el-button>
      </el-form-item>
    </el-form>
    <el-table
      style="width: 100%"
      border
      :data="tableData"
      :row-style="{ height: '50px' }"
      :header-cell-style="{ textAlign: 'center' }"
      :cell-style="{ textAlign: 'center' }"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="60" />
      <el-table-column fixed prop="id" label="ID" width="200" />
      <el-table-column prop="name" label="公告名" width="200" show-overflow-tooltip />
      <el-table-column prop="content" label="公告内容" width="280" show-overflow-tooltip />
      <el-table-column prop="time" label="发布时间" />
      <el-table-column prop="listView" label="缩略图" width="140">
        <template #default="scope">
          <img
            v-if="scope.row.listView"
            :src="`http://localhost:8080${scope.row.listView}`"
            alt="缩略图"
            style="max-width: 120px; max-height: 60px"
          />
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作">
        <template #default="scope">
          <el-button size="small" type="primary" @click="createOrUpdate(scope.row.id)"
            >编辑</el-button
          >
          <el-button size="small" type="danger" @click="remove(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-model="dialogFormVisible"
      :title="dialogTitle"
      width="800"
      style="margin-bottom: 60px"
      @close="handleClose"
    >
      <el-form :model="form" ref="formRef" label-width="120px">
        <el-form-item label="公告名" prop="name">
          <el-input v-model="form.name" autocomplete="off" placeholder="请输入公告名" />
        </el-form-item>
        <el-form-item label="公告内容" prop="content">
          <el-input
            v-model="form.content"
            type="textarea"
            autocomplete="off"
            placeholder="请输入公告内容"
          />
        </el-form-item>
        <el-form-item label="缩略图" prop="list_view">
          <el-upload
            class="upload-demo"
            action="http://localhost:8080/upload"
            :with-credentials="true"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            accept="image/*"
            list-type="picture-card"
          >
            <template v-if="form.list_view">
              <img
                  :src="`http://localhost:8080${form.list_view}`"
                alt="缩略图"
                style="width: 100%; height: 100%; object-fit: contain"
              />
              <span
                style="
                  position: absolute;
                  right: 4px;
                  top: 4px;
                  background: rgba(255, 255, 255, 0.7);
                  border-radius: 50%;
                "
              >
                <el-icon><Plus /></el-icon>
              </span>
            </template>
            <template v-else>
              <el-icon><Plus /></el-icon>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="发布时间" prop="time">
          <el-date-picker
            v-model="form.time"
            type="datetime"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择发布时间"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="add">确定</el-button>
        </div>
      </template>
    </el-dialog>
    <el-pagination
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[5, 10, 15, 20]"
      :size="size"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import BreadCrumb from '../components/BreadCrumb.vue'
import { getCurrentInstance, onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/counter'
import dayjs from 'dayjs'
import { Plus } from '@element-plus/icons-vue'
const axios = getCurrentInstance().appContext.config.globalProperties.axios
const userStore = useUserStore()
const tableData = ref([])
const total = ref(0)
const formatTimestamp = (timestamp: number) => {
  const date = new Date(timestamp)

  const year = date.getFullYear()
  const month = date.getMonth() + 1 // 月份从0开始，需要+1
  const day = date.getDate()

  // 时、分、秒补零
  const hours = date.getHours().toString().padStart(2, '0')
  const minutes = date.getMinutes().toString().padStart(2, '0')
  const seconds = date.getSeconds().toString().padStart(2, '0')

  // 格式: YYYY/MM/DD HH:mm:ss
  return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`
}
const currentPage = ref(1) // 当前页
const pageSize = ref(10) // 每页显示条目数
const size = 'default' // 分页大小
const bulletinName = ref('')
const inforText = ref('')
const handleSizeChange = (val) => {
  pageSize.value = val
  query()
}
const handleCurrentChange = (val) => {
  currentPage.value = val
  query()
}
const query = () => {
  axios.post('/announcement/page', {
    name: bulletinName.value,
    content: inforText.value,

  }, {
    params: {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    },
  }).then((resp) => {
    tableData.value = resp.data.list;
    total.value     = resp.data.total;
  });
};

const dialogFormVisible = ref(false)
const handleClose = () => {
  form.value = {
    id: '',
    name: '',
    content: '',
    list_view: '',
    time: '',
    sys_user_Id: '',
  }
}
const form = ref({
  id: '',
  name: '',
  content: '',
  list_view: '',
  time: '',
  sys_user_Id: '',
})
const dialogTitle = ref()
const createOrUpdate = (id) => {
  dialogFormVisible.value = true
  dialogTitle.value = id ? '编辑咨询公告' : '新增咨询公告'
  if (!id) {
    // 新增
    form.value = {
      id: '',
      name: '',
      content: '',
      list_view: '',
      time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      sys_user_Id: userStore.userInfo.userInfo.id || '',
    }
  } else {
    // 编辑
    axios.get(`announcement/${id}`).then((resp) => {
      form.value = {
        id: resp.data.id,
        name: resp.data.name,
        content: resp.data.content,
        list_view: resp.data.listView,
        time: resp.data.time,
        sys_user_Id: resp.data.sysUserId,
      }
    })
  }
}
const add = () => {
  console.log(1234)
  console.log(form.value)
  if (!form.value.sys_user_Id) {
    form.value.sys_user_Id = userStore.userInfo.id || ''
  }

  if (!form.value.name || !form.value.content || !form.value.list_view || !form.value.time) {
    ElMessage.error('请填写完整信息')
    return
  }
  if (!form.value.id) {
    console.log(form.value.id)

    axios
      .post(
        'announcement',
        {
          name: form.value.name,
          content: form.value.content,
          listView: form.value.list_view,
          time: form.value.time,
          sysUserId: form.value.sys_user_Id,
          del: 0,
        },
        {
          headers: {
            'Content-Type': 'application/json',
          },
        },
      )
      .then((resp) => {
        if (resp.code == 200) {
          ElMessage.success('新增成功')
          dialogFormVisible.value = false
        } else {
          ElMessage.error('新增失败')
        }
        query()
      })
      .catch(() => {
        query()
      })
  } else {
    // 编辑
    console.log('编辑')
    axios
      .put(
        'announcement',
        {
          id: form.value.id,
          name: form.value.name,
          content: form.value.content,
          listView: form.value.list_view,
          time: form.value.time,
          sysUserId: form.value.sys_user_Id,
          del: 0,
        },
        {
          headers: {
            'Content-Type': 'application/json',
          },
        },
      )
      .then((resp) => {
        if (resp.code == 200) {
          ElMessage.success('修改成功')
          dialogFormVisible.value = false
        } else {
          ElMessage.error('修改失败')
        }
        query()
      })
      .catch(() => {
        query()
      })
  }
}
const remove = (id) => {
  console.log('当前行的数据', id)
  ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios
        .delete(`announcement/${id}`)
        .then((resp) => {
          console.log('删除后：', resp)
          if (resp.code == 200) {
            ElMessage({
              message: '删除成功',
              type: 'success',
            })
          } else {
            ElMessage.error('删除失败')
          }
        })
        .finally(() => {
          query()
        })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
const ids = ref('')
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.id).join(',')
  console.log('批量删除的ids为:', ids.value)
}
const batchDelete = () => {
  console.log('ids', ids.value)
  if (!ids.value) {
    ElMessage.info('请选择要删除的数据')
    return
  }
  ElMessageBox.confirm('此操作将永久删除该数据, 是否继续?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      axios.delete(`announcement/batch?ids=${ids.value}`).then((res) => {
        ElMessage.success('删除成功')
        query()
      })
    })
    .catch(() => {
      ElMessage.info('已取消删除')
    })
    .finally(() => {
      query()
    })
}
onMounted(() => {
  query()
})
// 上传图片相关方法
const handleUploadSuccess = (response) => {
  console.log(response)
  if (response.code === 200 && response.data) {
    form.value.list_view = response.data
    console.log(1111)
    console.log(response.data)
    ElMessage.success('上传成功')
  } else {
    ElMessage.error('上传失败')
  }
}
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
  }
  return isImage
}
</script>

<style scoped></style>
